package com.finance.system.support.utils;


import com.finance.system.user.entity.UserEntity;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import javax.servlet.http.HttpSession;

/**
 *
 * 警告：由于这些方法与请求线程绑定，所以在使用这些方法时一定要在请求线程
 * (例如Controller或者被Controller间接调用的方法)中使用
 */
public enum SessionUtils {
    ;

    public static final String KEY_USER = "FINANCE_USER";
    public static HttpSession getSession() {
        return (HttpSession) RequestContextHolder.getRequestAttributes()
                .resolveReference(RequestAttributes.REFERENCE_SESSION);
    }

    public static Object getAttribute(String name) {
        return RequestContextHolder.getRequestAttributes()
                .getAttribute(name, RequestAttributes.SCOPE_SESSION);
    }

    public static void setAttribute(String name, Object value) {
        RequestContextHolder.getRequestAttributes()
                .setAttribute(name, value, RequestAttributes.SCOPE_SESSION);
    }

    public static Long getUserId() {
        return getAttribute(KEY_USER) == null ? null :
                ((UserEntity) getAttribute(KEY_USER)).getId();
    }


    public static boolean isUserLogged() {
        return getAttribute(KEY_USER) != null;
    }
}
